package com.yang.ogm.service;

import com.yang.ogm.pojo.MyPerson;
import com.yang.ogm.session.SessionFactoryUtils;
import org.neo4j.ogm.cypher.ComparisonOperator;
import org.neo4j.ogm.cypher.Filter;
import org.neo4j.ogm.cypher.Filters;
import org.neo4j.ogm.model.Result;
import org.neo4j.ogm.session.Session;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class PersonService {
    private Session session;

    public PersonService() {
        this.session = SessionFactoryUtils.getSessionFactory().openSession();
    }

    /**
     * 根据id查询用户数据
     * @param id
     * @return
     */
    public MyPerson queryPersonById(Long id) {
        return this.session.load(MyPerson.class, id);
    }


    public void savePerson(MyPerson person) {
        this.session.save(person);
    }
    public void deletePerson(MyPerson person) {
        this.session.delete(person);
    }

    public ArrayList<Long> deletePersonByName(String name) {
        Filter filter = new Filter("name", ComparisonOperator.EQUALS,name);
        return (ArrayList<Long>) this.session.delete(MyPerson.class,List.of(filter),true);
    }

    // depth默认为1。 -1加载全部数据 0仅加载当前节点属性 1加载实例将映射该对象的简单属性及其直接相关的对象
    public MyPerson queryPersonById(Long id, int depth) {
        return this.session.load(MyPerson.class,id,depth);
    }

    public List<MyPerson> queryPersonByName(String name) {
        Filter filter = new Filter("name",ComparisonOperator.EQUALS,name);
        return (List<MyPerson>) this.session.loadAll(MyPerson.class, filter);
    }

    public Result queryAllShortestPathsByCypher(String personName1, String persoName2){
        String cypher=
                """
                match(n:Person {name:$personName1}),
                (m:Person {name:$personName2}),
                p=allShortestPaths((n)-[*]-(m))
                return p
                """;
        HashMap<String, String> params = new HashMap<>();
        params.put("personName1", personName1);
        params.put("personName2", persoName2);
        return this.session.query(cypher,params);
    }
}
